package com.example.chatrecommendation.controller;

import com.example.chatrecommendation.bean.dto.StudentLoginDTO;
import com.example.chatrecommendation.bean.entity.Students;
import com.example.chatrecommendation.bean.vo.StudentLoginVO;
import com.example.chatrecommendation.service.impl.StudentsServiceImpl;
import com.example.chatrecommendation.tool.JwtUtil;
import com.example.chatrecommendation.tool.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

@RestController
//@CrossOrigin
@RequestMapping("/admin/student")
@Slf4j
public class StudentController {
	private final StudentsServiceImpl studentsServiceImpl;
	private final JwtUtil jwtUtil;

	public StudentController(StudentsServiceImpl studentsServiceImpl, JwtUtil jwtUtil) {
		this.studentsServiceImpl = studentsServiceImpl;
		this.jwtUtil = jwtUtil;
	}

	/**
	 * 登录
	 *
	 * @param studentLoginDTO 登录数据
	 * @return 用户信息
	 */
	@PostMapping("/login")
	public R<StudentLoginVO> login(@RequestBody StudentLoginDTO studentLoginDTO) {
		log.info("员工登录：{}", studentLoginDTO);

		Students students = studentsServiceImpl.login(studentLoginDTO);
//      校验是否登录成功
		if (students == null) {
			return R.err("用户名或密码错误");
		}
		//登录成功后，生成jwt令牌
		String token = jwtUtil.createJWT(students);

//        BaseContext.setCurrentId(students.getId());不需要设置线程，这个jwt是给前端存储的

		StudentLoginVO studentLoginVO = StudentLoginVO.builder()
				.id(students.getId())
				.studentAccount(students.getStudentAccount())
				.name(students.getName())
				.token(token)
				.build();

		return R.success(studentLoginVO);
	}
}
